import { FairyGUI, UnityEngine } from "csharp";

/**
 * 处理图的工具类
 * @author clong 2020.12.13
 */
export default class ImageUtils {

    /**
     * 分割纹理
     * @param tex 
     * @param source 
     * @param column 
     */
    public static splitTexture(tex: FairyGUI.NTexture, column: number): Array<FairyGUI.NTexture> {

        let width: number = tex.width;
        let height: number = tex.height;
        let sw: number = width / column;

        let source: UnityEngine.Texture2D = tex.nativeTexture as UnityEngine.Texture2D;
        
        let arr: Array<FairyGUI.NTexture> = [];
        for (let i = 0; i < column; i++) {
            let rect = new UnityEngine.Rect(i * sw, 0, sw, height);
            let tex2d = this.splitTexture2( source , rect );
            let stex = new FairyGUI.NTexture( tex2d , new UnityEngine.Rect(0,0,sw,height) );
            arr.push(stex);
        }
        return arr;
    }

    private static splitTexture2( source:UnityEngine.Texture2D , rect:UnityEngine.Rect ):UnityEngine.Texture2D{

        let rt: UnityEngine.RenderTexture = UnityEngine.RenderTexture.GetTemporary(
            source.width, source.height, 0);

        UnityEngine.Graphics.Blit(source, rt);

        let prev: UnityEngine.RenderTexture = UnityEngine.RenderTexture.active;
        UnityEngine.RenderTexture.active = rt;

        let png: UnityEngine.Texture2D = new UnityEngine.Texture2D( rect.width , rect.height, UnityEngine.TextureFormat.ARGB32, false);
        png.ReadPixels( rect , 0 , 0 );
        png.Apply();
        UnityEngine.RenderTexture.active = prev;
        console.log("splitTexture2-------> x: " + rect.x + " y: " + rect.y + " width: " + rect.width + " height: " + rect.height);
        return png;
    }
}